package edu.pe.cayetano.view.action;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ws.synopsis.frmwrk.common.BResult;
import edu.pe.cayetano.model.bo.UsuarioBO;
import edu.pe.cayetano.seccd.constantes.ConstantesMensajes;
import edu.pe.cayetano.seccd.constantes.ConstantesSECCD;
import edu.pe.cayetano.seccd.constantes.ConstantesSession;
import edu.pe.cayetano.util.EscribeLog;
import edu.pe.cayetano.view.form.LoginForm;


public class LoginAction extends BaseAction{
	
	private String page=null;
	
	/**
	 * Metodo que realiza el login del usuario a la aplicacion
	 * */
	public ActionForward login(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException{

		BResult 	ret				= new BResult();
		UsuarioBO 	usuarioBO 		= new UsuarioBO();
		try {
			HttpSession session = request.getSession(false);
			
			String 		vUsername = ((LoginForm) form).getUsername();
			String 		vPassword = ((LoginForm) form).getPassword();
		
			ret =	usuarioBO.validaUsuario(vUsername,vPassword);

			if(ret.getCode()==0 && ret.getObject()!=null){
				page=ConstantesSECCD.EXITO;
				session.setAttribute(ConstantesSession.USUARIO_LOGEADO,ret.getObject());
			}else{ 
				page=ConstantesSECCD.ERROR;
				EscribeLog.escribeLog(this.getClass().toString(), "login",ret.getMessage() , "");
				mostrarMensaje(request,ret.getMessage(),new String[0],"","");
			}
		}catch (Exception e) {
			page=ConstantesSECCD.ERROR;
			System.out.println("[SECCD][LoginAction][login] error generado por:"+e.getMessage());
			EscribeLog.escribeLog(this.getClass().toString(), "login",ret.getMessage() , e.toString());
			mostrarMensaje(request,ConstantesMensajes.ERROR_AMBIENTE,new String[0],"","");
		}
		return mapping.findForward(page);	
	}
	
	/**
	 * Metodo que realiza el logout del usuario de la aplicacion
	 * */
	public ActionForward logout(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
		try{
			page=ConstantesSECCD.EXITO;
			eliminarSession(request);
		}catch(Exception e){
			System.out.println("[SECCD][LoginAction][logout] error generado por:"+e.getMessage());
			page=ConstantesSECCD.ERROR;
		}
		return mapping.findForward(page);	
	}
	
	/**
	 * Metodo que direcciona a la pagina home
	 * */
	public ActionForward home(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
		System.out.println("[SECCD][LoginAction][home]");
		return mapping.findForward(page);	
	}
}